package com.resys.server.controller.customer;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.resys.entity.dto.TokenCustomerDto;
import com.resys.entity.po.*;
import com.resys.entity.query.CancellationrequestQuery;
import com.resys.entity.query.ReservationorderQuery;
import com.resys.entity.vo.OrdersVo;
import com.resys.entity.vo.ResponseVO;
import com.resys.exception.BusinessException;
import com.resys.server.controller.ABaseController;
import com.resys.server.websocket.WebSocketServer;
import com.resys.service.CancellationrequestService;
import com.resys.service.CustomerService;
import com.resys.service.MeetingroomService;
import com.resys.service.ReservationorderService;
import com.resys.service.impl.CustomerServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@RestController("manegeOrdersController")
@RequestMapping("/customer/manegeOrders")
@Api(tags= "客户模块-订单管理接口")
public class ManegeOrdersController extends ABaseController {
    @Resource
    private ReservationorderService reservationorderService;
    @Resource
    private CancellationrequestService cancellationrequestService;
    @Resource
    private MeetingroomService meetingroomService;
    @Resource
    private WebSocketServer webSocketServer;
    @Autowired
    private CustomerService customerService;

    @ApiOperation("取消预约并退款")
    @PostMapping("/cancel")
    public ResponseVO cancelOrder(Integer orderId){
        Reservationorder reservationorder = reservationorderService.getReservationorderByOrderId(orderId);
        if (reservationorder == null){
            throw new BusinessException("订单不存在，取消失败");
        }
        Customer customer = customerService.getCustomerByCustomerId(reservationorder.getCustomerId());
        CancellationrequestQuery quest = new CancellationrequestQuery();
        quest.setOrderId(orderId);
        quest.setStatus(0);
        List<Cancellationrequest> list = cancellationrequestService.findListByParam(quest);
        if(list.size()>0){
            throw new BusinessException("请勿重复申请");
        }
        Date now = new Date();
        Cancellationrequest cancell = new Cancellationrequest();
        cancell.setOrderId(orderId);
        cancell.setStatus(0);
        cancell.setRequestTime(new Date());
        if(new Date().before(reservationorder.getStartTime())){
            if(reservationorder.getStartTime().getTime()-now.getTime()>60*60*1000*72) {
                cancell.setRefundAmount(reservationorder.getTotalPrice());
            }else if(reservationorder.getStartTime().getTime()-now.getTime()>60*60*1000*48){
                cancell.setRefundAmount(reservationorder.getTotalPrice().multiply(new BigDecimal(0.75)));
            }else if(reservationorder.getStartTime().getTime()-now.getTime()>60*60*1000*24){
                cancell.setRefundAmount(reservationorder.getTotalPrice().multiply(new BigDecimal(0.25)));
            } else {
                throw new BusinessException("距离开始时间不足24小时，无法取消");
            }
        }
        cancellationrequestService.add(cancell);
        Map map = new HashMap();
        map.put("customer", customer.getClientName());
        map.put("content","有新的退款申请,订单号"+ orderId);
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
        return getSuccessResponseVO("取消成功");
    }
    @ApiOperation("查询已支付未使用订单列表")
    @GetMapping("/list")
    public ResponseVO listOrder(){
        TokenCustomerDto tokenCustomerDto = getTokenCustomer();
        ReservationorderQuery order = new ReservationorderQuery();
        order.setCustomerId(tokenCustomerDto.getCustomerId());
        order.setStatus(1);
        List<Reservationorder> list = reservationorderService.findListByParam(order);
        Iterator<Reservationorder> iterator = list.iterator();
        while (iterator.hasNext()) {
            Reservationorder od = iterator.next();
            if (od.getEndTime().before(new Date())) {
                    iterator.remove();
                    break;
            }

        }
        List<OrdersVo> result = Lists.newArrayList();
        for(Reservationorder od:list){
            Meetingroom room= meetingroomService.getMeetingroomByRoomId(od.getRoomId());
            OrdersVo vo = new OrdersVo();
            BeanUtils.copyProperties(od,vo);
            vo.setRoomName(room.getName());
            result.add(vo);
        }
        return getSuccessResponseVO(result);

    }
    @ApiOperation("查询所有订单列表列表")
    @GetMapping("/listall")
    public ResponseVO listall(){
        TokenCustomerDto tokenCustomerDto = getTokenCustomer();
        ReservationorderQuery order = new ReservationorderQuery();
        order.setCustomerId(tokenCustomerDto.getCustomerId());
        List<Reservationorder> list = reservationorderService.findListByParam(order);
        List<OrdersVo> result = Lists.newArrayList();
        for(Reservationorder od:list){
            Meetingroom room= meetingroomService.getMeetingroomByRoomId(od.getRoomId());
            OrdersVo vo = new OrdersVo();
            BeanUtils.copyProperties(od,vo);
            vo.setRoomName(room.getName());
            result.add(vo);
        }
        return getSuccessResponseVO(result);
    }
    @ApiOperation("查询已完成订单列表")
    @GetMapping("/listused")
    public ResponseVO listused(){
        TokenCustomerDto tokenCustomerDto = getTokenCustomer();
        ReservationorderQuery order = new ReservationorderQuery();
        order.setCustomerId(tokenCustomerDto.getCustomerId());
        order.setStatus(3);
        List<Reservationorder> list = reservationorderService.findListByParam(order);
        List<OrdersVo> result = Lists.newArrayList();
        for(Reservationorder od:list){
            Meetingroom room= meetingroomService.getMeetingroomByRoomId(od.getRoomId());
            OrdersVo vo = new OrdersVo();
            BeanUtils.copyProperties(od,vo);
            vo.setRoomName(room.getName());
            result.add(vo);
        }
        return getSuccessResponseVO(result);
    }
    @ApiOperation("查询未支付可直接取消订单列表")
    @GetMapping("/listcancel")
    public ResponseVO listcancel(){
        TokenCustomerDto tokenCustomerDto = getTokenCustomer();
        ReservationorderQuery order = new ReservationorderQuery();
        order.setCustomerId(tokenCustomerDto.getCustomerId());
        order.setStatus(0);
        List<Reservationorder> list = reservationorderService.findListByParam(order);
        Iterator<Reservationorder> iterator = list.iterator();
        while (iterator.hasNext()) {
            Reservationorder od = iterator.next();
            if (od.getLockedUntil().before(new Date())) {
                iterator.remove();
                break;
            }

        }
        List<OrdersVo> result = Lists.newArrayList();
        for(Reservationorder od:list){
            Meetingroom room= meetingroomService.getMeetingroomByRoomId(od.getRoomId());
            OrdersVo vo = new OrdersVo();
            BeanUtils.copyProperties(od,vo);
            vo.setRoomName(room.getName());
            result.add(vo);
        }
        return getSuccessResponseVO(result);

    }
    @ApiOperation("直接取消未支付订单")
    @PostMapping("/dircancel")
    public ResponseVO dircancel(Integer orderId){
        Reservationorder od= reservationorderService.getReservationorderByOrderId(orderId);
        od.setStatus(2);
        reservationorderService.updateReservationorderByOrderId(od,orderId);
        Meetingroom room = meetingroomService.getMeetingroomByRoomId(od.getRoomId());
        room.setStatus(0);
        meetingroomService.updateMeetingroomByRoomId(room,od.getRoomId());
        return getSuccessResponseVO("取消成功");
    }
}
